<?php

namespace app\chat\onmessage;

use app\chat\LiveMessage;
use app\common\lib\Util;
use app\zyhsapi\model\good_rtc_live\ZyhsGoodRtcLiveRecord;
use GatewayWorker\Lib\Gateway;
use Workerman\Lib\Timer;

class ZyhsConsultLogin
{
    private static $instance = null;
    private $isDebug = false;

    private function __construct($debug)
    {
        $this->isDebug = $debug;
    }

    public static function getInstance(bool $debug = false)
    {
        if (self::$instance === null)
        {
            return new self($debug);
        }

        return self::$instance;
    }

    public function handle(string $clientId = '', $message = [])
    {
        //token解析
        if (isset($message['params']))
        {
            $auth = LiveMessage::zyhsConsultAuth($message['params'], $message['is_astro'] ?? 0, $clientId);
            $auth['action'] = 'consult_login';
            if ($this->isDebug)
            {
                echo "\n";
                echo "==========onMessage action login start==========\n";
                echo "onMessage function client_id:( $clientId )\n";
                echo "auth:(" . json_encode($auth, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . ")\n";
                echo "==========onMessage action login end==========\n";
                echo "\n";
            }

            $uid = $auth['uid'];
            if ($auth['code'] === 200)
            {
                Timer::del($_SESSION['auth_timer_id']);// 认证成功，删除 30关闭连接定时器
                if ($uid !== 0)
                {
                    $clientUid = LiveMessage::WHO_TYPE_ZYHS_UID . ':' . $uid;
                    if (Gateway::isUidOnline($clientUid))
                    {
                        Gateway::unbindUid($clientId, $clientUid);
                    }
                    Gateway::bindUid($clientId, $clientUid);
                    if ($this->isDebug)
                    {
                        echo "\n bindUid=success\n";
                    }
                }

                $_SESSION['app_type'] = $auth['app_type'];
                $_SESSION['uid'] = $auth['uid'];
                $_SESSION['uen'] = $auth['uen'];
                $_SESSION['name'] = $auth['name'];
                $_SESSION['avatar'] = $auth['avatar'];
                $_SESSION['user_type'] = $auth['user_type'];    // 5 准有好事 用户
                $_SESSION['login_time'] = time();
                $_SESSION['version'] = $auth['version'];
                $_SESSION['live_type'] = $auth['live_type'];
                $_SESSION['live_record_id'] = $auth['live_record_id'];

                switch ($auth['live_type'])
                {
                    case 1: // 加入 房间
                        Gateway::joinGroup($clientId, 'zyhs_good_rtc_live_room_' . $auth['live_record_id']);
                        if ($uid)
                        {   // 发送 进入房间消息
                            LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_GOOD_RTC_LIVE_ROOM, 0, $auth['live_record_id']), LiveMessage::MSG_TYPE_POP_GOOD_RTC_LIVE_USER_JOIN, [
                                'user_info' => [
                                    'name' => $auth['name'],
                                ],
                                'des' => '进入房间',
                            ]);

                            $jobData = [
                                'app_type_num' => 1,
                                'type' => 'login',
                                'uid' => $auth['uid'],
                                'live_record_id' => $auth['live_record_id'],
                                'login_time' => $_SESSION['login_time'],
                                'app_type' => $auth['app_type'],
                            ];
                            // 记录用户登录信息
                            Util::queuePush('zyhs_good_rtc_live_login_or_out', $jobData);
                            // 添加 更新在线人数 队列
                            (new ZyhsGoodRtcLiveRecord())->addSyncOnlineNumQueue($auth['live_record_id']);
                        }
                        break;
                }
            } else
            {
                //发送给当前用户登录失败的消息
                Gateway::sendToCurrentClient(LiveMessage::show($auth['code'], $auth['msg'], $message['action']));
            }
        } else
        {
            Gateway::sendToCurrentClient(LiveMessage::show(0, 'params 不能为空！', $message['action']));
        }
    }
}
